#include "widgetiic.h"
#include "ui_widgetiic.h"

#include <qmessagebox.h>

WidgetIIC::WidgetIIC(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WidgetIIC)
{
    ui->setupUi(this);

	QIntValidator *validator = new QIntValidator(1, 9999, this);
	ui->etPeriod->setValidator(validator);

    timerIICQuery = new QTimer(this);
    connect(timerIICQuery, SIGNAL(timeout()), this, SLOT(slotiicQuery()));

}

WidgetIIC::~WidgetIIC()
{
    delete timerIICQuery;
    delete ui;
}

void WidgetIIC::SetUartRecerver(serialportio *tReceiver,QString productModal)
{
    this->sensorRecver_ = tReceiver;
    this->mProductModal = productModal;

    this->sensorRecver_->serialPort_->setRequestToSend(false);

    if(this->mProductModal=="TF02-Pro"||this->mProductModal=="TF03")
    {
        ui->btnLowConsumption->setDisabled(true);
    }
	if (this->mProductModal == "TF03")
	{
		ui->cbOutputFormat->clear();
		ui->cbOutputFormat->addItem("9Byte(cm)");
		ui->cbOutputFormat->addItem("字符格式(m)");
	}
}

bool WidgetIIC::CheckComState()
{
    if(sensorRecver_==nullptr)
        return false;

    if(!sensorRecver_->isOpen())
    {
        QMessageBox::warning(NULL, "Error", tr(u8"未连接Com口"));
        return false;
    }

    return true;
}


bool WidgetIIC::CheckComStateNoMessage()
{
    if(sensorRecver_==nullptr)
        return false;

    if(!sensorRecver_->isOpen())
    {
        return false;
    }

    return true;
}


/**
 * @brief WidgetIIC::on_btnIICAddress_clicked
 * 设置IIC地址
 */
void WidgetIIC::on_btnIICAddress_clicked()
{

     if(!CheckComState()) return;

     uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);
     uint iicNewAddr = ui->etIICAddress->text().toInt(nullptr,16);

	 qDebug() << "IIC地址设定，由原地址："<< iicCurAddr<<"设定为新地址"<< iicNewAddr;

     if(this->mProductModal=="TF-Luna"||this->mProductModal=="TFmini-S"||this->mProductModal=="TFmini-Plus")
     {
         if(sensorRecver_->send_iic_setaddr(iicCurAddr,iicNewAddr))
         {
             qDebug("设定成功");
             QMessageBox::information(NULL, tr(u8"提示"), tr(u8"IIC地址设定成功"));
         }
         else
         {
			 qDebug("设定失败");
             QMessageBox::warning(NULL, tr(u8"提示"), tr(u8"IIC地址设定失败，请重试"));
         }
     }
     else if(this->mProductModal=="TF02-Pro")
     {
         if(sensorRecver_->send_iic_setaddr_pro(iicCurAddr,iicNewAddr))
         {
			 qDebug("设定成功");
             QMessageBox::information(NULL, tr(u8"提示"), tr(u8"IIC地址设定成功"));
         }
         else
         {
			 qDebug("设定失败");
             QMessageBox::warning(NULL, tr(u8"提示"), tr(u8"IIC地址设定失败，请重试"));
         }

     }


}



void WidgetIIC::on_btnSaveConfig_clicked()
{
       if(!CheckComState()) return;

	   qDebug() << "保存配置";

       ui->lbConfigSvResult->setText("");
        uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);
      if(this->mProductModal=="TF-Luna"||this->mProductModal=="TFmini-S"||this->mProductModal=="TFmini-Plus")
      {
          if(sensorRecver_->send_iic_save_settings(iicCurAddr))
          {
			  qDebug() << "配置保存成功";
              ui->lbConfigSvResult->setText(tr(u8"配置保存成功！"));
          }
          else{
			  qDebug() << "配置保存失败";
             ui->lbConfigSvResult->setText(tr(u8"配置保存失败！"));
          }
      }
      else if(this->mProductModal=="TF02-Pro")
      {
          //TODO==>无协议
          if(sensorRecver_->send_iic_save_settings_pro(iicCurAddr))
          {
			  qDebug() << "配置保存成功";
              ui->lbConfigSvResult->setText(tr(u8"配置保存成功！"));
          }else{
			  qDebug() << "配置保存失败";
             ui->lbConfigSvResult->setText(tr(u8"配置保存失败！"));
          }
      }
}

void WidgetIIC::on_btnFrameFreq_clicked()
{

   if(!CheckComState()) return;

    uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);

	qDebug() << "帧率设定为:"<< ui->cbFrameFreq->currentText();

   if(this->mProductModal=="TF-Luna"||this->mProductModal=="TFmini-S"||this->mProductModal=="TFmini-Plus")
   {
       if(sensorRecver_->send_iic_frame_rate(iicCurAddr,ui->cbFrameFreq->currentText().toUShort()))
       {
          qDebug("帧率设定成功！");
          QMessageBox::information(NULL, tr(u8"提示"), tr(u8"帧率设定成功"));

       }else{
           qDebug("帧率设定失败！");
           QMessageBox::warning(NULL, tr(u8"提示"), tr(u8"帧率设定失败"));
       }
   }
   else if(this->mProductModal=="TF02-Pro") {

       if(sensorRecver_->send_iic_frame_rate_pro(iicCurAddr,ui->cbFrameFreq->currentText().toUShort()))
       {
          qDebug("帧率设定成功！");
          QMessageBox::information(NULL, tr(u8"提示"), tr(u8"帧率设定成功"));

       }else{
           qDebug("帧率设定失败！");
           QMessageBox::warning(NULL, tr(u8"提示"), tr(u8"帧率设定失败"));
       }

   }



}


void WidgetIIC::on_btnOutputFormat_clicked()
{
    if(!CheckComState()) return;

    E_OutputFormat_Type outputFormat;

	qDebug() << "输出格式设定为"<< ui->cbOutputFormat->currentText();
    if(ui->cbOutputFormat->currentIndex()==0)
    {
        outputFormat = E_OutputFormat_Type::FORMAT_9BYTECM;
		
    }
    else if(ui->cbOutputFormat->currentIndex()==1)
    {
        outputFormat = E_OutputFormat_Type::FORMAT_9BYTEMM;
    }
    else if(ui->cbOutputFormat->currentIndex()==2)
    {
        outputFormat = E_OutputFormat_Type::FORMAT_PIX;
    }

      uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);

     if(this->mProductModal=="TF-Luna"||this->mProductModal=="TFmini-S"||this->mProductModal=="TFmini-Plus")
     {

        if(sensorRecver_->send_iic_output_format(iicCurAddr,outputFormat))
        {
           qDebug("输出格式设定成功！");
           QMessageBox::information(NULL, tr(u8"提示"), tr(u8"设定成功！"));


        }else{
			qDebug("输出格式设定失败！");
           QMessageBox::warning(NULL, tr(u8"提示"), tr(u8"设定失败"));
        }
     }
      else if(this->mProductModal=="TF02-Pro") {

         if(sensorRecver_->send_iic_output_format_pro(iicCurAddr,outputFormat))
         {
			 qDebug("输出格式设定成功！");
            QMessageBox::information(NULL, tr(u8"提示"), tr(u8"设定成功！"));


         }else{
			 qDebug("输出格式设定失败！");
            QMessageBox::warning(NULL, tr(u8"提示"), tr(u8"设定失败"));
         }
     }

}


void WidgetIIC::on_btnLowConsumption_clicked()
{
   if(!CheckComState()) return;

  

   uint sampleRate = ui->cbLowConsumption->currentText().toUInt();
   uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);

   qDebug() << "输出低功耗频率为" << sampleRate;

   if(this->mProductModal=="TF-Luna"||this->mProductModal=="TFmini-S"||this->mProductModal=="TFmini-Plus")
   {

       if(sensorRecver_->send_iic_low_consumption(iicCurAddr,sampleRate))
       {
          qDebug("低功耗设定成功！");
          QMessageBox::information(NULL, "提示", tr(u8"低功耗设定成功"));

       }else{
           qDebug("低功耗设定失败！");
          QMessageBox::warning(NULL, "提示", tr(u8"低功耗设定失败"));
       }
   }
   else if(this->mProductModal=="TF02-Pro") {

      //无低功耗功能


   }


}

void WidgetIIC::on_btnGetMeasureResult_clicked()
{

    unsigned short distancecm  = 0;

    uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);

    if(!CheckComState()) return;

	qDebug() << "获取距离";

    if(this->mProductModal=="TF-Luna"||this->mProductModal=="TFmini-S"||this->mProductModal=="TFmini-Plus")
    {

        if(sensorRecver_->send_iic_getdistancecm(iicCurAddr,distancecm))
        {
			qDebug() << "获取距离成功："<< distancecm;
            ui->etDistance->setText(QString::number(distancecm));


        }else{
           ui->etDistance->setText("获取距离失败");
		   qDebug() << "获取距离失败";

        }
    }
    else if(this->mProductModal=="TF02-Pro")
    {
        if(sensorRecver_->send_iic_getdistancecm_pro(iicCurAddr,distancecm))
        {
			qDebug() << "获取距离成功：" << distancecm;
           ui->etDistance->setText(QString::number(distancecm));

        }else{
           ui->etDistance->setText("获取距离失败");
		   qDebug() << "获取距离失败";

        }


    }



}


void WidgetIIC::on_btnSystemReset_clicked()
{

    if(!CheckComState()) return;

	qDebug() << "系统复位";

    QMessageBox  msgBox;
     uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);
   if(sensorRecver_->send_iic_soft_reset(iicCurAddr))
   {
	   qDebug() << "系统复位成功";
      //QMessageBox::information(NULL, tr(u8"提示"), tr(u8"复位成功！"));
      ui->lbResetResult->setText(tr(u8"复位成功！"));


   }else{
	   qDebug() << "系统复位失败";
      //QMessageBox::warning(NULL, tr(u8"提示"), tr(u8"复位失败"));
       ui->lbResetResult->setText(tr(u8"复位失败！"));
   }


}


void WidgetIIC::on_btnFactoryReset_clicked()
{
     if(!CheckComState()) return;
	 qDebug() << "恢复出厂设置";
     uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);
     if(sensorRecver_->send_iic_restore_default(iicCurAddr))
     {
         ui->lbFactoryReset->setText(tr(u8"恢复出厂成功"));
		 qDebug() << "恢复出厂设置成功";
     }else{
         ui->lbFactoryReset->setText(tr(u8"恢复出厂失败"));
		 qDebug() << "恢复出厂设置失败";
     }
}


void WidgetIIC::on_btnStartQuery_clicked()
{
	try
	{
		if (!CheckComState()) return;
		qDebug() << "开始轮询距离";
		if (!timerIICQuery->isActive())
		{
			int period = ui->etPeriod->text().toInt();

			if (period == 0)
			{
				QMessageBox::warning(NULL, tr(u8"提示"), tr("轮询周期不可以设置为0"));
				return;
			}

			sensorRecver_->iicFreq_ = 1000 / period;

			timerIICQuery->setInterval(period);
			timerIICQuery->start();

			ui->btnStartQuery->setEnabled(false);
		}
	}
	catch (QString ex) {
		qErrnoWarning(1001, ex.toStdString().data());
		QMessageBox::warning(NULL, tr(u8"提示"), ex);
	}
  



}

void WidgetIIC::on_btnStopQuery_clicked()
{
    if(timerIICQuery->isActive())
    {
        timerIICQuery->stop();
         ui->btnStartQuery->setEnabled(true);
    }

}

void WidgetIIC::slotiicQuery()
{
     if(!CheckComStateNoMessage())
     {
        qDebug("Serial port is not opened");
        return;
     }
     unsigned short distancecm  = 0;
     uint iicCurAddr = ui->etCurIICAddress->text().toInt(nullptr,16);

     if(this->mProductModal=="TF-Luna"||this->mProductModal=="TFmini-S"||this->mProductModal=="TFmini-Plus")
     {
         if(sensorRecver_->send_iic_querydistancecm(iicCurAddr))
         {
            qDebug("iic data sampling signal sent successful");

         }else{

            qDebug("iic data sampling signal sent fail");
         }
     }else
     {
         if(sensorRecver_->send_iic_querydistance_pro(iicCurAddr))
         {
            qDebug("iic data sampling signal sent successful");

         }else{

            qDebug("iic data sampling signal sent fail");
         }
     }

}
